<script type="text/javascript" src="public/js/epoly.js"></script>

<!-- ZOOM MAP WITH ZOOMOOZ  
<link rel="stylesheet" href="public/css/zoomooz.css" type="text/css" media="screen" />

<script type="text/javascript" src="public/js/zoom/sylvester.js"></script>
<script type="text/javascript" src="public/js/zoom/purecssmatrix.js"></script>
<script type="text/javascript" src="public/js/zoom/jquery.animtrans.js"></script>
<script type="text/javascript" src="public/js/zoom/jquery.zoomooz.js"></script>
<!-- END LIBRARY ZOOM -->
<script type="text/javascript">
    //<![CDATA[

    var iconBlue = new GIcon(); 
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

    var iconRed = new GIcon(); 
    iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
    iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconRed.iconSize = new GSize(12, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

    var rendererOptions = {    
        draggable: true    
    };

    var map
    var gdir;
    
    var customIcons = [];    
    customIcons["restaurant"] = iconBlue;
    customIcons["bar"] = iconRed;

    function load() {
      if (GBrowserIsCompatible()) {
        //
        // == SET TOOLBAR TIM KIEM TRONG MAP
        var mapOptions = {
            googleBarOptions : {
                style : "new",
            }
        }
        
        map = new GMap2(document.getElementById("map_canvas"),mapOptions);
        // == TAO DIRECTIONS (DUONG DI)
        gdir = new GDirections(map, document.getElementById("directions"));
       
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(15.1227767,108.800514), 14);
        
        // == DI CUNG VOI TOOLBAR
        map.setUIToDefault();
        map.enableGoogleBar();
                      
        <?php
        //
        // == XÁC ĐỊNH ĐƯỜNG VÀ VẼ ĐƯỜNG ĐI TRÊN MAP BẰNG CÁCH RÊ MARKER
        
        switch($_GET['fn']){
            case 'onemark' : {                
         ?>                 
            // == ve 1 marker                  
                var gmarkers = [];
                var side_bar_html;
                function createMarker(point,name,html,max) {
                    var marker = new GMarker(point);
                    GEvent.addListener(marker, "click", function() {
                        marker.openInfoWindowHtml(html,{maxContent:max});
                    });
                    
                    // save the info we need to use later for the side_bar
                    gmarkers.push(marker);
                    side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
                    return marker;
                }
                
                function myclick(i) {
                    GEvent.trigger(gmarkers[i],"click");
                }
             
                
                <?php 
                if(!empty($this->infoMark) && is_array($this->infoMark)){                    
                
                ?>
                
                    var label   = "<?php echo $this->infoMark['name']; ?>";
                    var lat     = "<?php echo $this->infoMark['vido']; ?>";
                    var lng     = "<?php echo $this->infoMark['kinhdo']; ?>";
                    var html    = "<?php echo $this->infoMark['gioithieu']; ?>";
                    var maxContent = "test thu<?php //include 'Upload/files/'.$this->infoMark['noidung'];?>";
                    var point = new GLatLng(lat,lng);
                    
                    // create the marker
                    var marker = createMarker(point,label,html,maxContent);
                    map.addOverlay(marker);
                                    
                <?php 
                }else{
                ?>
                    document.getElementById("map-message").innerHTML = "<center><strong><font size='6'>Địa điểm này chưa được cập nhập!!</font></strong></center>";    
                <?php
                } 
                ?>                
                
        <?php
            }  
                break;
                
            case 'drag' : { 
        ?>
        
            //
            // == FUNCTION DIRECTION BY DRAGG  MARKER
            
            var dirn1 = new GDirections();
            var dirn2 = new GDirections();
            var dirn3 = new GDirections();
            
            var firstpoint = true;
            var gmarkers = []; // array makers
            var gpolys = [];   // array các đường (polyline)
            var lastindex = 0;
            
            GEvent.addListener(map, "click", function(overlay,point) {
                
                // == When the user clicks on a the map, get directiobns from that point to itself ==
                if (!overlay) {
                    if (firstpoint){
                        dirn1.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
                    } else {
                        dirn1.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
                    }
                }
            });
            
            function calculateDistance() {                
                var dist = 0;
                for (var i=0; i<gpolys.length; i++) {
                    dist += gpolys[i].Distance();
                }
                //
                // === 1 mile(dam) = 1609.344 (m)
                // === 1 km = 1000 meters
                document.getElementById("total_direction").innerHTML="Độ dài đoạn đường: "+(dist/1000).toFixed(2)+" km. ("+(dist/1609.344).toFixed(2)+" miles (dặm)).";
            }
            
            // == when the load event completes, plot the point on the street
            GEvent.addListener(dirn1,"load", function() {                
                //
                // snap to last vertex (đỉnh) in the polyline
                var n = dirn1.getPolyline().getVertexCount();
                var p=dirn1.getPolyline().getVertex(n-1);
                var marker=new GMarker(p,{draggable:true});
                GEvent.addListener(marker, "dragend", function() {
                    lastIndex = marker.MyIndex;
                    var point = marker.getPoint();
                    
                    if (lastIndex>0) {
                        // recalculate the polyline preceding this point
                        dirn2.loadFromWaypoints([gmarkers[lastIndex-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
                    }
                    
                    if (lastIndex<gmarkers.length-1) {
                        // recalculate the polyline following this point
                        dirn3.loadFromWaypoints([point.toUrlValue(6),gmarkers[lastIndex+1].getPoint()],{getPolyline:true});
                    }
                });
                
                map.addOverlay(marker);
                // store the details
                marker.MyIndex=gmarkers.length;
                gmarkers.push(marker);
                // Đặt marker đầu tiên if haven't marker first
                if (!firstpoint) { 
                    map.addOverlay(dirn1.getPolyline());
                    gpolys.push(dirn1.getPolyline());
                    calculateDistance();
                }
                
                firstpoint = false;
                
                if (gmarkers.length>1 && gmarkers.length<26) {
                    document.getElementById("link").style.display="";
                } else {
                    document.getElementById("link").style.display="none";
                }
            });
            
            // == move the polyline preceding (trước) this point 
            GEvent.addListener(dirn2,"load", function() {
                // snap to last vertex (đỉnh) in the polyline
                var n = dirn2.getPolyline().getVertexCount();
                var p=dirn2.getPolyline().getVertex(n-1);
                gmarkers[lastIndex].setPoint(p);
                // remove the old polyline
                map.removeOverlay(gpolys[lastIndex-1]);
                // add the new polyline and overlay các đỉnh
                map.addOverlay(dirn2.getPolyline());
                gpolys[lastIndex-1] = (dirn2.getPolyline());
                calculateDistance();
            });                
            
            //
            // == move the polyline following this point ==
            GEvent.addListener(dirn3,"load", function() {
                // snap to first vertex in the polyline
                var p=dirn3.getPolyline().getVertex(0);
                gmarkers[lastIndex].setPoint(p);
                // remove the old polyline
                map.removeOverlay(gpolys[lastIndex]);
                // add the new polyline
                map.addOverlay(dirn3.getPolyline());
                gpolys[lastIndex] = (dirn3.getPolyline());
                calculateDistance();
            });

            GEvent.addListener(dirn1,"error", function() {
                GLog.write("Failed: "+dirn1.getStatus().code);
            });
              
            GEvent.addListener(dirn2,"error", function() {
                GLog.write("Failed: "+dirn2.getStatus().code);
            });
            
            GEvent.addListener(dirn3,"error", function() {
                GLog.write("Failed: "+dirn3.getStatus().code);
            });

            //
            // == END CASE DRAG        
        <?php
            } break;
            //
            // == END XÁC ĐỊNH ĐƯỜNG VÀ VẼ ĐƯỜNG ĐI TRÊN MAP BẰNG CÁCH RÊ MARKER//
        
            default : { 
                // == HIỂN THỊ CHỨC NĂNG MẶC ĐỊNH (LOAD TOÀN BỘ MARKER)                    
                //
                // == VE ALL MARKER ON MAP
                if(!empty($this->infoData)){
                    foreach($this->infoData as $value){                                       
        ?>    
                        var name    = "<?php echo  $value['name']; ?>" ;
                        var address = "<?php echo  $value['address']; ?>" ;        
                        var lat     = "<?php echo  $value['lat']; ?>" ;
                        var lng     = "<?php echo  $value['lng']; ?>" ;         
                        var marker = createMarker(name,lat,lng, address);
                                    
                        //       
                        map.addOverlay(marker);
                            
        <?php
                    }// == end foreach
                     
                }// == END IF (VE MARKER ON MAP)
                
                //
                //VE DUONG DI GIUA 2 DIEM DUOC XAC DINH TRONG KHI TIM DUONG
                if(!empty($this->from) && !empty($this->to)){           
        ?>
                    var arrPoints = new Array();
            	    var fromPoint = new GLatLng(<?php echo $this->from[0]['lat']." , ".$this->from[0]['lng']; ?>);
                    var toPoint = new GLatLng(<?php echo $this->to[0]['lat']." , ".$this->to[0]['lng']; ?>);
            	    
                    //
                    // === ve duong
            	    arrPoints.push(fromPoint);
            	    arrPoints.push(toPoint);    	   
            	    gdir.loadFromWaypoints(arrPoints);            
                    //
                    // == end ve duong
                
            <?php
            
                }elseif(!empty($this->fromDirection) && !empty($this->toDirection)){                
            ?>
                    arrPoints = new Array();                        
            	    fromPoint = new GLatLng(<?php echo $this->fromDirection['lat']." , ".$this->fromDirection['lng']; ?>);
                    toPoint   = new GLatLng(<?php echo $this->toDirection['lat']." , ".$this->toDirection['lng']; ?>);
            	    
                    //
                    // === ve duong
            	    arrPoints.push(fromPoint);
            	    arrPoints.push(toPoint);    	   
            	    gdir.loadFromWaypoints(arrPoints);            
                    //
                    // == end ve duong
                
            <?php
            
                }// == END if DIRECTION
                
            }// == END CASE Defaul
                break;                   
            }
    ?>
        }
    }
    //]]>
  </script>
  <script type="text/javascript">
    $(document).ready(function(){
        
        var streetData  = new Array();
        var latData     = new Array();
        var lngData     = new Array();
        var soDuongData = new Array();
        <?php 
        foreach($this->autoComplete as $value){                                       
        ?>  //
            // LAY DU LIEU CHO AUTOCOMPLATE 
            var name    = "<?php echo  $value['name']; ?>";
            var address = "<?php echo  $value['address'];?>";        
            var lat     = "<?php echo  $value['lat']; ?>";
            var lng     = "<?php echo  $value['lng']; ?>";         
            
            //
            //set du lieu cho arr de dung trong autocomplate
            if(address != "" )  streetData.push(address);            
            if(lat != "")       latData.push(lat)  ; 
            if(lng != "")       lngData.push(lng);
         
                            
        <?php 
        } 
        ?>
        //
        // == AUTO COMPLETE DIA CHI ĐƯỜNG
        $( "#fromAddress1" ).autocomplete({
			source: streetData
		});        
        $( "#toAddress1" ).autocomplete({
			source: streetData
		});
        // == FORM TOOLTIP ON MAP
        $( "#tipFTo" ).autocomplete({
			source: streetData
		});
        //
        // == ZOOM ELEMENT 
        /*$(".map-zoom").click(function(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            $(this).zoomTo({debug:true});
        });
        
        $(window).click(function(evt) {
            evt.stopPropagation();
            $("body").zoomTo({targetsize:1.0});
        });*/
        
        
    });
  </script>


  <body onload="load()" onunload="GUnload()">
    <div class="other-func">
        <p>Chức năng khác: 
                <br />
            <a href="./?rt=map&fn=drag" > Tìm lộ trình đường đi giữa các địa điểm bất kỳ</a>
                <br />
            <a href="./?rt=map&fn=&wh=alldulich">Hiển thị tất cả các địa điểm du lịch</a>
                <br />
            <a href="./?rt=map&fn=">Hiển thị tất cả các địa điểm</a>
        
        
        </p>
       
    </div>
    <br />
    <div id="map-message"></div>
    <br />
    
    <div class="dir-route">
        <h2>Tìm lộ trình đi giữa hai địa điểm trên GoogleMap </h2>
        
        <form action="./?rt=map&fn" method="post" onsubmit="" class="validatesearch" >        
            <table width="500">
                <tr>
                    <th class="map-form-title" align="center" width="150">Nơi bạn đang đứng:&nbsp;</th>
                    <th class="map-form-title" align="center">&nbsp;Nơi bạn muốn tới:&nbsp;</th>                
                </tr>
               <tr>
                    <th class="map-form-title">
                        <input name="fromStreet" class="inp required" type="text" id="fromAddress1" name="txtfrom1" /> 
                    </th>  
                    <th class="map-form-title">                  
                        <input class="inp required" type="text" id="toAddress1" name="txtto1" />
                    </th>
               </tr>                              
                <tr>               
                   <th colspan="2">    
                        <input class="getMap" name="cmdXd_duong" type="submit" value="Xác định đường!" onclick=""  />
                   </th>
                </tr>
            </table>             
        </form>
    </div>
    
    <br/>
    
    <table class="directions">
        <tr>
            <th class="map-form-title" >Đường đi</th>
            <th class="map-form-title">Bản đồ</th>
        </tr>

        <tr>
            <td valign="top">
                <div id="link">
                    <div style="font-size: 1.2em;" id="total_direction"></div> 
                </div>
                <div id="directions" style="width: 150px"></div>
                
                
            </td>
            <td valign="top"><div id="map_canvas" class="map-zoom" style="width: 500px !important; height: 600px !important; background: black !important; z-index: 1000 !important;"></div>
            </td>    
        </tr>
    </table> 
  </body>
</html>